package com.joseph.websocket.component;

import com.joseph.websocket.util.JedisUtil;
import org.redisson.Redisson;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.params.SetParams;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @Description: 为IM服务器分配唯一服务器ID
 * @Author: Joseph_Mok
 * @Date: Created 2018/12/1 18:38
 */
@Component("serverIdInitializer")
public class ServerIdInitializer implements InitializingBean {

    final Timer timer = new Timer();

    private Integer serverId;

    public static final String XINYUN_IM_SERVER_ID_LOCK_KEY = "XINYUN_IM_SERVER_ID_LOCK_KEY";

    public static final String XINYUN_IM_SERVER_ID_KEY = "XINYUN_IM_SERVER_ID_KEY_";

    public static final String USE_FLAG = "USED";

    @Override
    public void afterPropertiesSet() throws Error {
//        Redisson lock = new (JedisUtil.getJedis(), XINYUN_IM_SERVER_ID_LOCK_KEY, 3000, 3000);
//        try {
//            if (lock.acquire()) {
//                for (int i = 0; i < 20; i++) {
//                    final String key = XINYUN_IM_SERVER_ID_KEY + i;
//                    if (JedisUtil.getJedis().get(key) == null) {
//                        JedisUtil.getJedis().set(key, USE_FLAG, SetParams.setParams().ex(30));
//                        serverId = i;
//                        timer.scheduleAtFixedRate(new TimerTask() {
//                            @Override
//                            public void run() {
//                                try {
//                                    JedisUtil.getJedis().set(key, USE_FLAG, SetParams.setParams().ex(30));
//                                } catch (Exception e) {
//                                    //短信告警
//                                }
//                            }
//                        }, 30000, 30000);
//                        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                JedisUtil.getJedis().del(key);
//                            }
//                        }, "SERVER_ID_THREAD"));
//                        break;
//                    }
//                }
//            }
//        } catch (Exception e) {
//            throw new Error("初始化服务器Id异常");
//        } finally {
//            lock.release();
//            if (serverId == null) {
//                throw new Error("初始化服务器Id异常");
//            }
//        }
    }

    public Integer getServerId() {
        return serverId;
    }

    public void setServerId(Integer serverId) {
        this.serverId = serverId;
    }

}
